//
//  AddStyleViewController.m
//  linkingGame
//
//  Created by zw wu on 15/4/19.
//  Copyright (c) 2015年 com.jinWu. All rights reserved.
//

#import "AddStyleViewController.h"
#import "AddStyleTipView.h"
#import "AddStyleCell.h"

#import "AddNewItemViewController.h"

@interface AddStyleViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,AddStyleCellDelegate,UIDocumentInteractionControllerDelegate>

@property (nonatomic,retain) AddStyleTipView *addStyleTipView;
@property (nonatomic,retain) UICollectionView *collectionView;
@property (nonatomic,retain) NSMutableArray *itemList;
@property (nonatomic,retain) UIDocumentInteractionController *documentController;
@property (nonatomic,retain) NSString *ownExpressionPath;

@end

@implementation AddStyleViewController

- (BOOL)prefersStatusBarHidden
{
    return YES;//隐藏为YES，显示为NO
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refreshTableUI];
    [self resetAllSubViewFrame];
    
    NSString *selectedItemList = [[NSUserDefaults standardUserDefaults]objectForKey:@"linkingGameSelectedExpression"];
    if (selectedItemList.length == 0)
    {
        selectedItemList = @"doge";
        [[NSUserDefaults standardUserDefaults] setObject:selectedItemList forKey:@"linkingGameSelectedExpression"];
    }
    
    if ([self.itemList containsObject:selectedItemList])
    {
        NSInteger newSelectItem = [self.itemList indexOfObject:selectedItemList];
        NSIndexPath *newSelectIndexPath = [NSIndexPath indexPathForItem:newSelectItem inSection:0];
        [self.collectionView selectItemAtIndexPath:newSelectIndexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"linkingGameOwnExpression"];
    self.ownExpressionPath = path;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:path])
    {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];  
    }
    
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    }
    
    self.view.backgroundColor = [UIColor grayColor];
    
    AddStyleTipView *addStyleTipView = [[AddStyleTipView alloc]init];
    [self.view addSubview:addStyleTipView];
    self.addStyleTipView = addStyleTipView;
    [addStyleTipView release];
    
    addStyleTipView.backgroundColor = [UIColor orangeColor];
    
    [addStyleTipView.backBtn addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
    [addStyleTipView.addBtn addTarget:self action:@selector(addNewStyle) forControlEvents:UIControlEventTouchUpInside];
    
    NSMutableArray *itemList = [[NSMutableArray alloc]initWithCapacity:0];
    self.itemList = itemList;
    [itemList release];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                            collectionViewLayout:flowLayout];
    
    self.collectionView = collectionView;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [flowLayout release];
    [collectionView release];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    //注册cell和ReusableView（相当于头部）
    [self.collectionView registerClass:[AddStyleCell class] forCellWithReuseIdentifier:@"KAddStyleCell"];
}

- (void)resetAllSubViewFrame
{
    CGSize mainSize = self.view.bounds.size;
    CGRect addStyleTipViewRect,collectionViewRect;
    if (isPhone())
    {
        addStyleTipViewRect = CGRectMake(0, 0, mainSize.width, 88);
    }
    else
    {
        if (isLandscape())
        {
            addStyleTipViewRect = CGRectMake(0, 0, mainSize.width, 120);
        }
        else
        {
            addStyleTipViewRect = CGRectMake(0, 0, mainSize.width, 180);
        }
    }
    
    collectionViewRect = CGRectMake(0, addStyleTipViewRect.size.height, mainSize.width, mainSize.height - addStyleTipViewRect.size.height);
    
    if (!CGRectEqualToRect(addStyleTipViewRect, self.addStyleTipView.frame))
    {
        self.addStyleTipView.frame = addStyleTipViewRect;
        [self.addStyleTipView refreshUI];
    }
    
    if (!CGRectEqualToRect(collectionViewRect, self.collectionView.frame))
    {
        self.collectionView.frame = collectionViewRect;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    self.addStyleTipView = nil;
    self.collectionView = nil;
    self.itemList = nil;
    self.documentController = nil;
    self.ownExpressionPath = nil;
    
    [super dealloc];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self.documentController dismissMenuAnimated:NO];
    [self resetAllSubViewFrame];
}

- (void)refreshTableUI
{
    [self.itemList removeAllObjects];
    [self.itemList addObject:@"doge"];
    
    NSArray *tmplist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.ownExpressionPath error:nil];
    for (NSString *filename in tmplist)
    {
        NSString *fullPath = [self.ownExpressionPath stringByAppendingPathComponent:filename];
        BOOL isDirectory = NO;
        if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDirectory])
        {
            if (isDirectory)
            {
                NSArray *tmplist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fullPath error:nil];
                if (tmplist.count >= KMinItemCount)
                {
                    [self.itemList addObject:fullPath];
                }
                else
                {
                    [[NSFileManager defaultManager]removeItemAtPath:fullPath error:nil];
                }
            }
        }
    }
    
    [self.collectionView reloadData];
}

- (void)goToBack
{
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)addNewStyle
{
    NSString *folderName = nil;
    do
    {
        double timeTag = (int)[[NSDate date] timeIntervalSince1970];
        folderName = [NSString stringWithFormat:@"user_%lld",(long long)timeTag];
        NSString *path = [self.ownExpressionPath stringByAppendingPathComponent:folderName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:path])
        {
            [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            break;
        }
        
    }while (YES);
    
    AddNewItemViewController *addNewItemVC = [[AddNewItemViewController alloc]init];
    addNewItemVC.pathId = folderName;
    [self.navigationController pushViewController:addNewItemVC animated:NO];
    [addNewItemVC release];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemList.count;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"KAddStyleCell";
    AddStyleCell *cell = (AddStyleCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    
    if (!cell)
    {
        NSLog(@"无法创建CollectionViewCell时打印，自定义的cell就不可能进来了。");
    }
    
    cell.row = indexPath.row;
    cell.delegate = self;
    cell.pathId = [self.itemList objectAtIndex:indexPath.row];

    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize cellSize = CGSizeMake(120, 120);
    if (isPhone())
    {
        cellSize = CGSizeMake(90, 90);
    }
    
    return cellSize;
}

//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets cellEdgeInsets = UIEdgeInsetsMake(20, 30, 20, 30);
    if (isPhone())
    {
        cellEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
    }
    
    return cellEdgeInsets;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
{
    if (isPhone())
    {
        return 10;
    }
    
    return 30;
}

#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"选择%ld",(long)indexPath.row);
    
    //AddStyleCell *cell = (AddStyleCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSLog(@"...");
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark -AddStyleCellDelegate
- (void)goToEdit:(AddStyleCell *)cell
{
    
}

- (void)goToDelete:(AddStyleCell *)cell
{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [[NSFileManager defaultManager]removeItemAtPath:cell.pathId error:nil];
    NSArray *deleteArr = [NSArray arrayWithObject:indexPath];

    NSInteger newSelectItem = indexPath.row + 1;
    if (indexPath.row == (self.itemList.count - 1))
    {
        newSelectItem = indexPath.row - 1;
    }
    
    NSIndexPath *newSelectIndexPath = [NSIndexPath indexPathForItem:newSelectItem inSection:0];
    if (cell.selected)
    {
        [self.collectionView selectItemAtIndexPath:newSelectIndexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    }
    
    [self.itemList removeObjectAtIndex:indexPath.row];
    [self.collectionView deleteItemsAtIndexPaths:deleteArr];
}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)goToShare:(AddStyleCell *)cell
{
    //将地图数据和 图片数据集合成一个文件。
    NSMutableArray* imageArray = [[NSMutableArray alloc] init];
    UIImage* image = nil;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *imagePath = [docDir stringByAppendingPathComponent:cell.pathId];
    
    NSArray *tmplist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:imagePath error:nil];
    
    for (NSString *filename in tmplist)
    {
        NSString* filePath = [imagePath stringByAppendingPathComponent:filename];
        image = [UIImage imageNamed:filePath];
        NSData* imageData = UIImageJPEGRepresentation(image, 1);
        [imageArray addObject:imageData];
    }
    
    NSString *path = [docDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.llk", cell.pathId]];
    [NSKeyedArchiver archiveRootObject:imageArray toFile:path];
    
    UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path]];
    documentController.delegate = self;
    [documentController presentOpenInMenuFromRect:cell.frame
                                           inView:cell.superview
                                         animated:YES];
    self.documentController = documentController;
}

- (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller
{
    self.documentController = nil;
}

@end
